<template>
  <div class="project-container">
    <el-card class="page-header">
      <template #header>
        <div class="card-header">
          <span>模板管理</span>
          <div class="header-actions">
            <el-input v-model="keyword" placeholder="搜索模板名称" clearable @clear="onSearch" @keyup.enter.native="onSearch" style="width: 240px"/>
            <el-button type="primary" @click="handleCreate" :disabled="isProjectUser">创建模板</el-button>
          </div>
        </div>
      </template>
      
      <div class="table-container">
        <el-table :data="templates" height="calc(100vh - 250px)">
          <el-table-column prop="name" label="模板名称" />
          <el-table-column prop="protocolNumber" label="方案编号" width="150" />
          <el-table-column prop="version" label="版本号" width="100" />
          <el-table-column prop="versionDate" label="版本日期" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatCreateTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="400" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)" :disabled="isProjectUser">编辑</el-button>
              <el-button link type="primary" @click="handlePreview(row)">预览</el-button>
              <el-button link type="primary" @click="handleManageForms(row)" :disabled="isProjectUser">配置访视和表单</el-button>
              <el-button link type="primary" @click="handleViewJson(row)">JSON</el-button>
              <el-button link type="danger" @click="handleDelete(row)" :disabled="isProjectUser">删除</el-button>
              <el-button link type="success" @click="handleGenerateWord(row)">生成Word</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <el-pagination
        class="pagination-container"
        :current-page="pagination.currentPage"
        :page-size="pagination.itemsPerPage"
        :total="pagination.totalItems"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- JSON 查看对话框 -->
    <el-dialog v-model="jsonDialogVisible" title="模板 JSON" width="60%">
      <pre class="json-content">{{ jsonContent }}</pre>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="jsonDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="copyJson">复制</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import ProjectModal from '@/components/modal/ProjectModal.vue'
import ProjectPreviewDialog from '@/components/modal/ProjectPreviewDialog.vue'
import { useProjectStore } from '@/stores/project'
import { addDialog } from '@/components/gDialog'

const router = useRouter()
const authStore = useAuthStore()
const isProjectUser = computed(() => authStore.getUserRole === 'project_user')
const projectStore = useProjectStore()
const templates = computed(() => projectStore.projects)
const pagination = computed(() => projectStore.pagination)

// JSON dialog state
const jsonDialogVisible = ref(false)
const jsonContent = ref('')

// 格式化创建时间显示
const formatCreateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 搜索关键词
const keyword = ref('')

// 获取模板列表
const getTemplates = async (page = 1, limit = 10) => {
  try {
    await projectStore.fetchProjects({ isTemplate: true, page, limit, search: keyword.value?.trim() })
  } catch (error) {
    ElMessage.error('获取模板列表失败')
  }
}

// 触发搜索
const onSearch = () => {
  getTemplates(1, pagination.value.itemsPerPage)
}

// 分页处理
const handleSizeChange = (val) => {
  getTemplates(1, val)
}

const handleCurrentChange = (val) => {
  getTemplates(val, pagination.value.itemsPerPage)
}

// 创建模板
const handleCreate = () => {
  addDialog({
    title: '创建模板',
    width: '800px',
    component: ProjectModal,
    props: {
      isEdit: false
    },
    callBack: async (data) => {
      if (!data) return
      try {
        const templateData = {
          ...data,
          isTemplate: true,
          createTime: new Date().toISOString()
        }
        await projectStore.createProject(templateData)
        ElMessage.success('创建模板成功')
        getTemplates()
      } catch (error) {
        ElMessage.error('创建模板失败')
      }
    }
  })
}

// 编辑模板
const handleEdit = (row) => {
  addDialog({
    title: '编辑模板',
    width: '600px',
    component: ProjectModal,
    props: {
      isEdit: true,
      editData: row
    },
    callBack: async (data) => {
      if (!data) return
      try {
        await projectStore.updateProject({ ...data, id: row.id, isTemplate: true })
        ElMessage.success('更新成功')
        getTemplates()
      } catch (error) {
        ElMessage.error('更新失败')
      }
    }
  })
}

// 模板预览
const handlePreview = (row) => {
  addDialog({
    title: `模板预览 - ${row.name}`,
    width: '90%',
    component: ProjectPreviewDialog,
    props: {
      projectData: row
    },
    callBack: (action, data) => {
      if (action === 'generate') {
        handleGenerateWord(data)
      }
    }
  })
}

// 配置访视和表单
const handleManageForms = (row) => {
  router.push({
    name: 'ProjectFormManager',
    params: {
      projectId: row._id || row.id
    }
  })
}

// 查看 JSON
const handleViewJson = (row) => {
  jsonContent.value = JSON.stringify(row, null, 2)
  jsonDialogVisible.value = true
}

const copyJson = () => {
  try {
    navigator.clipboard.writeText(jsonContent.value)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 删除模板
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该模板吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await projectStore.deleteProject(row._id)
      ElMessage.success('删除成功')
      getTemplates()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 生成 Word
const handleGenerateWord = async (row) => {
  if (!row.configSections || row.configSections.length === 0) {
    ElMessage.warning('请先为该模板配置章节和表单');
    return;
  }
  try {
    await projectStore.generateWord(row)
    ElMessage.success('Word 文件生成成功')
  } catch (error) {
    ElMessage.error('Word 文件生成失败')
  }
}

// 状态显示
const getStatusType = (status) => {
  const map = {
    active: 'success',
    completed: 'info',
    paused: 'warning'
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    active: '进行中',
    completed: '已完成',
    paused: '已暂停'
  }
  return map[status] || status
}

// 初始化
getTemplates()
</script>

<style scoped>
.project-container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 120px); /* Adjust height based on your layout */
}
.page-header {
  flex-shrink: 0;
  margin-bottom: 20px;
}
.table-container {
  flex-grow: 1;
  overflow-y: auto;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
.page-header {
  margin-bottom: 20px;
}
.pagination-container {
  flex-shrink: 0;
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.json-content {
  background-color: #f5f7fa;
  padding: 16px;
  border-radius: 4px;
  font-family: monospace;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 60vh;
  overflow-y: auto;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 